<?php

namespace app\models\product;

use app\models\constant\Status;
use app\models\Images;
use Yii;

/**
 * This is the model class for table "product_category".
 *
 * @property int $id
 * @property int $parent_id 父级
 * @property string $name 名称
 * @property int $image_id image id
 * @property int $sort
 * @property int $status 1开 0关 -99删除
 * @property int $merchant_id
 * @property string $create_time
 * @property string $update_time
 */
class ProductCategory extends \yii\db\ActiveRecord
{
    // use Status;

    /**
     * status list
     * @var int[]
     */
    public static $statusMapping = [
        'ALL'       => -1,
        'OK'        => 1,
        'CLOSE'     => 0,
        'DELETE'    => -99,
    ];

    /**
     * status display list
     * @var int[]
     */
    public static $statusMappingDisplay = [
        '全部'       => -1,
        '正常'       => 1,
        '待审核'       => 0,
        // '删除'       => -99,
    ];

    /**
     * Status list
     *
     * @return array
     */
    public static function statusList()
    {
        $list = [];
        foreach (self::$statusMappingDisplay as $key => $value) {
            $list[] = [
                'label' => $key,
                'value' => $value
            ];
        }

        return $list;
    }

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'product_category';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['parent_id', 'image_id', 'sort', 'status'], 'integer'],
            [['name'], 'required'],
            [['create_time', 'update_time'], 'safe'],
            [['name'], 'string', 'max' => 255],

            [['merchant_id'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'parent_id' => 'Parent ID',
            'name' => 'Name',
            'image_id' => 'Image ID',
            'sort' => 'Sort',
            'status' => 'Status',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
        ];
    }

    public static function clear()
    {
        $list = self::find()
            ->where(['status' => self::$statusMapping['DELETE']])
            ->all();
        foreach ($list as $category) {
            $image = Images::findOne(['id' => $category->image_id]);
            if ($image) {
                $image->delete();
            }
            $category->delete();
            // echo 'delete image id > ', $image->id, "\n";
            echo 'delete category id > ', $category->id, "\n";
        }
    }

    /**
     * Save timestamp
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    /**
     * with image
     *
     * @return \yii\db\ActiveQuery
     */
    public function getImage()
    {
        return $this->hasOne(Images::class, ['id' => 'image_id']);
    }

    public function getParent()
    {
        return $this->hasOne(self::class, ['id' => 'parent_id']);
    }

    public function getChildren()
    {
        return $this->hasMany(self::class, ['parent_id' => 'id']);
    }

    public static function getCategoriesByParent($parent_id = 0, $getChildren = false, $_result = [])
    {
        $list = self::find()
            ->where(['parent_id' => $parent_id])
            ->andWhere(['!=', 'status', self::$statusMapping['DELETE']])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
            ->asArray()
            ->all();

        foreach ($list as $item) {
            // 处理死循环
            foreach ($_result as $value) {
                if ($value['id'] == $item['id']) {
                    return $_result;
                }
            }
            array_push($_result, $item);

            // 处理子分类
            if ($getChildren) {
                $_result = self::getCategoriesByParent($item['id'], $getChildren, $_result);
            }
        }

        return $_result;
    }

    public function getProduct()
    {
        return $this->hasMany(Product::class, ['category_id' => 'id']);
            // ->where(['status' => Product::$statusMapping['OK']]);
    }
}
